package com.example.shiro;

import com.example.model.auto.User;
import com.example.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author lyj
 * @Title: UserRealm
 * @ProjectName demo
 * @Description: TODO
 * @date 2020/12/3 23:04
 */

public class UserRealm extends AuthorizingRealm {
    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行授权逻辑");
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        User user=(User)subject.getPrincipal();
        User curUser = userService.findById(user.getId());
      // info.addStringPermission("user:add");
        info.addStringPermission(curUser.getPerms());
        return info;
    }

    @Autowired
    private IUserService userService;
    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行认证");
//        String name="aa";
//        String password="123";
//        UsernamePasswordToken passwordToken=(UsernamePasswordToken)token;
//        if (!passwordToken.getUsername().equals(name)) {
//            return null;
//        }

        //1.判断用户名
        UsernamePasswordToken passwordToken=(UsernamePasswordToken)token;

        User user = userService.findByName(passwordToken.getUsername());
        if (user==null) {
            return null;  //用户名不存在，shiro底层会抛出UnknowAccountException
        }
        //2.判断密码
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
